package com.bocai.grainshop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bocai.common.constant.ProductConstant;
import com.bocai.grainshop.product.dao.AttrAttrgroupRelationDao;
import com.bocai.grainshop.product.dao.AttrGroupDao;
import com.bocai.grainshop.product.dao.CategoryDao;
import com.bocai.grainshop.product.entity.AttrAttrgroupRelationEntity;
import com.bocai.grainshop.product.entity.AttrGroupEntity;
import com.bocai.grainshop.product.entity.CategoryEntity;
import com.bocai.grainshop.product.service.AttrAttrgroupRelationService;
import com.bocai.grainshop.product.service.CategoryService;
import com.bocai.grainshop.product.vo.AttrRespVo;
import com.bocai.grainshop.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bocai.common.utils.PageUtils;
import com.bocai.common.utils.Query;

import com.bocai.grainshop.product.dao.AttrDao;
import com.bocai.grainshop.product.entity.AttrEntity;
import com.bocai.grainshop.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private AttrAttrgroupRelationDao relationDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryService categoryService;

    @Resource
    private AttrAttrgroupRelationService attrgroupRelationService;

    //this表示当前对象  controller调用service时this表示当前service对象
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 根据分组id查找关联的所有基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = entities.stream().map((attr) -> attr.getAttrId()).collect(Collectors.toList());

        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }


    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1)、当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2)、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3)、从当前分类的所有属性中移除这些属性；
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    /**
     * @Author: SunJinbo
     * @Description  级联保存
     * @Param [attr]
     * @return void
     * @Data Created in 2022/3/25 15:06
     */
    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //赋值类属性
        BeanUtils.copyProperties(attr,attrEntity);

        this.save(attrEntity);
        if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            //调用save方法后attrEntity给主键attrID赋值
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrSort(0);

            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            relationEntity.setAttrId(attrEntity.getAttrId());

            attrgroupRelationService.save(relationEntity);
        }
    }

    /**
     * @Author: SunJinbo
     * @Description  规格参数检索
     * @Param [params, catelogId]
     * @return com.bocai.common.utils.PageUtils
     * @Data Created in 2022/3/25 17:02
     */
    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type","base".equalsIgnoreCase(type)
                        ?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():
                        ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if(catelogId!=0)
        {
            wrapper.eq("catelog_id",catelogId);
        }

        String key = (String) params.get("key");

        if(StringUtils.hasText(key)){

            wrapper.and((obj) -> obj.eq("attr_id",key).or().like("attr_name",key));
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);
        //获取分页获取的数据
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> respVoList = records.stream().map((obj) -> {
            //把收集的数据的中的部分信息赋值给AttrResVo对象
            AttrRespVo respVo = new AttrRespVo();

            //赋值对象
            BeanUtils.copyProperties(obj, respVo);

            //根据关系中间表查组id
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",obj.getAttrId()));

           if("base".equalsIgnoreCase(type)){
               //查组名
               if(relationEntity!=null && relationEntity.getAttrGroupId()!=null){

                   AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                   //设置组名
                   if (attrGroupEntity != null) {

                       respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                   }
               }
           }

            //查分类
            CategoryEntity categoryEntity = categoryDao.selectById(respVo.getCatelogId());

            //设置分类名
            if (categoryEntity != null) {

                respVo.setCatelogName(categoryEntity.getName());
            }
            return respVo;
        }).collect(Collectors.toList());

        pageUtils.setList(respVoList);

        return pageUtils;
    }

    /**
     * @Author: SunJinbo
     * @Description  规格参数的修改 展示信息回显
     * @Param [attrId]
     * @return com.bocai.grainshop.product.vo.AttrRespVo      
     * @Data Created in 2022/3/25 19:37
     */
    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        //创建需要整理的类
        AttrRespVo attrRespVo = new AttrRespVo();
        //查询出数据库实际的attrId的数据
        AttrEntity byId = this.getById(attrId);
        //赋值部分基本数据
        BeanUtils.copyProperties(byId,attrRespVo);
        //判断是否是销售属性
        if(byId.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //从关联表中查询出attr_Id的关系信息
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            //如果查询出结果
            if(relationEntity!=null){
                //从分组表中查询出此分组信息
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                //如果查询结果不为空
                if(attrGroupEntity!=null){
                    //设置组名
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //获取分类路劲
        Long[] catelogPath = categoryService.findCatelogPath(byId.getCatelogId());
        //设置路径
        attrRespVo.setCatelogPath(catelogPath);
        //查询出此分类的数据
        CategoryEntity categoryEntity = categoryDao.selectById(byId.getCatelogId());
        //设置分类名
        attrRespVo.setCatelogName(categoryEntity.getName());
        //返回结果
        return attrRespVo;
    }

    /**
     * @Author: SunJinbo
     * @Description  规格参数具体修改
     * @Param [attr]
     * @return void
     * @Data Created in 2022/3/25 19:40
     */
    @Override
    @Transactional
    public void updateAttr(AttrRespVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //基本表的修改
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //根据操作数据库的返回值判断是新增还是修改
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrSort(0);
            relationEntity.setAttrId(attrEntity.getAttrId());
            Integer attr_id = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if(attr_id > 0){
                //修改关联表
                relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            }else {
                relationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public List<Long> selectAttrByAttrId(List<Long> list) {
        return this.baseMapper.selectAttrByAttrId(list);
    }

}